#!/usr/bin/python

from pysqlite2 import dbapi2 as sqlite3
from datetime import datetime

class Cache:
	def __init__(self,cache,debug=False):
		self.debug = debug
		if (debug):
			self.conn = sqlite3.connect(':memory:')
		else:
			self.conn = sqlite3.connect('cache/%s.sql' % cache)
		try:
			self.conn.execute("""CREATE TABLE Cache (
				id INTEGER NOT NULL PRIMARY KEY,
				type TEXT NOT NULL,
				name TEXT NOT NULL,
				updated DATE,
				data BLOB NOT NULL)""")
		except Exception,e:
			if self.debug:
				print "EXCEPTION in table generation",e
				raise Exception("Exception in table generation",e)
			
	def AddCache(self,type,name,data):
		self.conn.execute("INSERT INTO Cache VALUES (NULL,?,?,?,?)",(type,name,datetime.now(),data,))
		self.conn.commit()
		
	def DelCache(self,type,name):
		self.conn.execute("DELETE FROM Cache WHERE Type=? AND Name=?",(type,name,))
		self.conn.commit()
		
	def GetCache(self,type,name):
		conn = self.conn.cursor()
		conn.execute("SELECT data FROM Cache WHERE Type=? AND Name=?",(type,name,))
		try:
			return conn.fetchone()[0]
		except:
			return None
			
